package id.co.shuba.spamobile.task;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.Encryptor;
import id.co.shuba.spamobile.WSException;
import id.co.shuba.spamobile.data.BaseDB;
import id.co.shuba.spamobile.data.MaintenanceVisitDB;
import id.co.shuba.spamobile.data.StandardDB;
import id.co.shuba.spamobile.data.ProspectDB;
import id.co.shuba.spamobile.model.MaintenanceVisitInfo;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.services.WebServiceHelper;
import id.co.shuba.spamobile.util.Base64;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

public class DownloadMaintenanceVisitTask extends
		BaseProgressTask {
	WebServiceHelper _ws;
	SQLiteDatabase _db;	
	INotify _notify;
	UserInfo _user;
	String _imei;

	public DownloadMaintenanceVisitTask(WebServiceHelper ws,
			SQLiteDatabase db, INotify notify, UserInfo user, String imei) {
		_ws = ws;
		_db = db;		
		_notify = notify;
		_user = user;
		_imei = imei;
	}	

	@Override
	protected AsyncTaskResult<Void> doInBackground(Object... params) {
		try {						
			Map<String, Object> properties = new HashMap<String, Object>();
			String maxDate = MaintenanceVisitDB.getMaxDate(_db);
			if (maxDate == null) maxDate = "1990-01-01";			
			
			Encryptor enc = new Encryptor(
					Encryptor.ENC_AES,
					Encryptor.ENC_AES, App.createCompleteKey(_user.getEncryptionKey()), App.IV);
			String pwd = enc.decryptText(_user.getPassword());	
			
			properties.put("unitCode", _user.getUnitCode());
			properties.put("aoCode", _user.getAoCode());
			properties.put("updateDate", maxDate);
			properties.put("nip", _user.getNip());
			properties.put("password", pwd);
			properties.put("imei", _imei);
			properties.put("token", _user.getToken());
			
			
			publishStatus("Updating...");
			String result = _ws.Call("GetMaintenanceVisit", properties).toString();
			publishProgress(20);
			
			publishStatus("Extracting...");
			String strJSON = new String(Base64.decode(result, Base64.GZIP)); 			
			publishProgress(30);			
			
			JSONObject res = new JSONObject(strJSON);
			String error = res.getString("error");
			if (error.length() > 0 && !error.equals("null"))
				throw new WSException(error);
				
			JSONArray jsonArray = res.getJSONArray("result");					
			publishProgress(50);
									
			publishStatus("Uploading...");
			int length = jsonArray.length();						
			for (int i = 0; i < length; i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				MaintenanceVisitInfo info = new MaintenanceVisitInfo();
				info.setId(jsonObject.getString("id"));
				info.setAoCode(jsonObject.getString("aoCode").trim());
				info.setUnitCode(jsonObject.getString("unitCode"));
				info.setNoAccount(jsonObject.getString("noAccount"));
				info.setDateVisit(jsonObject.getString("dateVisit"));
				info.setDebtorName(jsonObject.getString("debtorName"));
				info.setUpdateDate(jsonObject.getString("updateDate"));
				info.setObjectiveOfVisit(jsonObject.getString("objectiveOfVisit"));				
				info.setEntryBy(jsonObject.getString("entryBy"));
				info.setEntryDate(jsonObject.getString("entryDate"));
				info.setUpdateBy(jsonObject.getString("updateBy"));				
				info.setUpdateDate(jsonObject.getString("updateDate"));
				info.setIsDeleted(jsonObject.getString("isDeleted"));
				info.setIsUpload("0");
				
				MaintenanceVisitDB.addOrUpdate(_db, info);
				
				int progress = (int)(50 + (50f * (((float)i)/length)));
				publishStatus(String.format("Uploading...%d/%d", i, length));
				publishProgress(progress);
			}
			
			publishStatus("Done!");
			publishProgress(0);
			
			return new AsyncTaskResult<Void>((Void) null);
		} catch (WSException we) {
			publishStatus(we.getMessage());
			publishProgress(0);
			return new AsyncTaskResult<Void>(we);
		} catch (Exception e) {
			Log.e("Download", e.getMessage(), e);
			if (e.getMessage().contains("Unable to resolve") || e.getMessage().contains("failed to connect")) {
				publishStatus("Tidak dapat tersambung ke server");
			} else {
				publishStatus(e.getMessage());
			}
			publishProgress(0);
			return new AsyncTaskResult<Void>(e);
		}		
	}

	@Override
	public String getTitle() {		
		return "Maintenance Visit";
	}
	
	@Override
	protected void onPostExecute(AsyncTaskResult<Void> result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		
		_notify.notifyFinish(result.getError());
	}
	
	@Override
	protected void onCancelled(AsyncTaskResult<Void> result) {		
		super.onCancelled(result);
		
		Log.d("DownloadOptionTask", "Task cancelled");
	}
}
